package com.cuit.qx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cuit.qx.bean.WarnSound;
import com.cuit.qx.job.TimingProcessorJob;
import com.cuit.qx.service.WarnSoundService;
import com.cuit.qx.utils.ReturnData;
import com.cuit.qx.utils.ReturnStateCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author ：long
 * @date ：Created in 2021/2/25 0025 17:45
 * @description：
 */

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/warnSound")
public class UpFileController {

    private static final Logger LOG = LoggerFactory.getLogger(TimingProcessorJob.class);


    @Value("${uploadWarnSoundUrl}")
    private String uploadWarnSoundUrl;
    @Value("${ip}")
    private String ip;
    @Value("${upload}")
    private String upload;
    @Value("${server.port}")
    private String port;

    @Autowired
    private WarnSoundService warnSoundService;

    @PostMapping("uploadFile")
    public ReturnData upload(MultipartFile file){
        try {
            if (file.isEmpty()){
                return new ReturnData(ReturnStateCode.FAILED.getCode(), "文件为空");
            }
            //获取文件名
            String fileName = file.getOriginalFilename();
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("audio_name",fileName);
            WarnSound one = warnSoundService.getOne(queryWrapper);
            if (one!=null){
                return new ReturnData(ReturnStateCode.FAILED.getCode(), "文件已存在");
            }
            LOG.info("上传的文件名："+fileName);
            //获取文件后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            if(suffixName.equals("mp3")){
                return new ReturnData(ReturnStateCode.FAILED.getCode(), "文件格式错误，请传mp3格式文件");
            }
            //设置文件存储路径
            String filePath = "f:/upload/";
            String path = filePath+fileName;
            File dest = new File(path);
            //检测是否存在该目录
            if (!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            //写入文件
            file.transferTo(dest);
            WarnSound warnSound = new WarnSound();
            warnSound.setAudioName(fileName);
            warnSound.setDescrible(fileName + "的说明");
            warnSound.setStatus("0");
            warnSound.setAudition("0");
            warnSound.setPath(getWarnSoundUrl(fileName));

            warnSoundService.save(warnSound);
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), "预警声音导入成功!");
        } catch (IOException e) {
            LOG.error("音频文件上传异常",e);
        }
        return new ReturnData(ReturnStateCode.FAILED.getCode(), "上传文件失败");
    }

    public String getWarnSoundUrl(String fileName) {
        //获取预警声音上传根目录长度
        int uploadLength = upload.length();
        //获取预警声音路径长度
        int uploadFilesPdfLength = uploadWarnSoundUrl.length();
        String s = uploadWarnSoundUrl.substring(uploadLength, uploadFilesPdfLength);
        String productUrl = normalizeUrl(s + File.separator + fileName);
        // 获取预警声音的路径
        String path = ip + ":" + port + productUrl;
        return path;
    }

    public String normalizeUrl(String path) {
        String placeholder = "6445BF55-95C4-41F9-8235-34CE3ED9146D";
        String result = path.replaceAll("\\\\+", "/");
        result = result.replaceAll("/+", "/");
        result = result.replaceAll("/+", placeholder);
        return result.replace(placeholder, "/");
    }

}
